from datetime import datetime
from typing import Optional
from uuid import UUID, uuid4

from bisheng.database.base import session_getter
from bisheng.database.models.base import SQLModelSerializable
from sqlalchemy import Column, DateTime, String, Text, text, desc, func
from sqlalchemy.dialects.mysql import MEDIUMTEXT
from sqlmodel import Field, SQLModel
from typing import List

class AlarmStatusBase(SQLModelSerializable):
    id: UUID = Field(nullable=False, primary_key=True, description='唯一ID')
    chat_id: str = Field(sa_column=Column(String(length=255), default=''), description='会话id')
    group_id: str = Field(sa_column=Column(String(length=255), default=''), description='告警id')
    status: str = Field(sa_column=Column(String(length=255), default=''), description='某个会话某个告警的状态')
    create_time: Optional[datetime] = Field(
        sa_column=Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP')))
    update_time: Optional[datetime] = Field(sa_column=Column(DateTime,
                                                             nullable=False,
                                                             index=True,
                                                             server_default=text('CURRENT_TIMESTAMP'),
                                                             onupdate=text('CURRENT_TIMESTAMP')))


class AlarmStatus(AlarmStatusBase, table=True):
    id: UUID = Field(default_factory=uuid4, primary_key=True, unique=True)



class AlarmStatusDao:
    @staticmethod
    def create_alarm_status(alarm_status: AlarmStatus) -> AlarmStatus:
        with session_getter() as session:
            # 确保 alarm_status 有一个 UUID
            if not alarm_status.id:
                alarm_status.id = uuid4()
            if not alarm_status.status:
                alarm_status.status = "0"

            session.add(alarm_status)
            session.commit()
            session.refresh(alarm_status)
            return alarm_status

    @staticmethod
    def update_alarm_status(chat_id: str,status: str,update_time :str) -> Optional[AlarmStatus]:
        """
        更新会话告警状态
        Args:
            chat_id: 要更新的会话记录的 UUID。
            status: 新的状态值。
            update_time
        Returns:
            如果找到并成功更新会话告警，则返回更新后的 AlarmStatus 对象。
            如果没有找到会话告警记录，则返回 None。
        """
        with session_getter() as session:
            alarm_status = session.query(AlarmStatus).filter(AlarmStatus.chat_id == chat_id,AlarmStatus.status == status).one_or_none()
            if not alarm_status:
                return None  # 没有找到会话告警记录
            alarm_status.status = status
            if update_time:
                alarm_status.update_time = datetime.strptime(update_time, "%Y-%m-%d %H:%M:%S")
            else:
                alarm_status.update_time = datetime.now()
            session.add(alarm_status)
            session.commit()
            session.refresh(alarm_status)
            return alarm_status

    @staticmethod
    def get_by_chat_id(chat_id: str,status: Optional[str] = None) -> Optional[List[AlarmStatus]]:
        """
        查找会话告警根据chat_id
        Args:
            chat_id: 要更新的会话记录的 UUID。
            status: 状态，为空时返回整个会话告警列表
        Returns:
            返回会话告警记录。
            如果没有找到会话告警记录，则返回 None。
        """
        with session_getter() as session:
            if not status:
                alarm_status = session.query(AlarmStatus).filter(AlarmStatus.chat_id == chat_id).order_by(desc(AlarmStatus.update_time)).all()
            else:
                alarm_status = session.query(AlarmStatus).filter(AlarmStatus.chat_id == chat_id,AlarmStatus.status == status).one_or_none()
            return alarm_status

